package com.edu.admin.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.edu.admin.common.BaseContextHandler;
import com.edu.admin.entity.SysAdmin;
import com.edu.admin.enums.ExceptionEnum;
import com.edu.admin.service.AdminService;
import com.edu.admin.service.RoleMenuService;
import com.edu.admin.common.RestResult;
import com.edu.admin.vo.AdminVo;



/**
 * 系统管理
 * 
 * @author Wangjiong
 *
 */
@RestController
@RequestMapping(value = "/sys", name = "系统管理")
public class SysController {
	//private static final Logger log = LoggerFactory.getLogger(SysController.class);
	@Value("${token.header}")
    private String tokenHeader;
	@Autowired
	private AdminService adminService;
	@Autowired
	private RoleMenuService roleMenuService;


	/**
	 *
	 * @apiGroup sys
	 * @api {post} /sys/login 用户登录
	 * @apiVersion 1.0.0
	 * @apiName login
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		    "username": "admin",
		    "password": "123456" 
		
		}
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": {
		        "adminId": 2,
		        "account": "18612345678",
		        "adminName": "张三",
		        "phone": "18612345678",
		        "roleId": 2,
		        "schoolId": 1,
		        "classesId": 1,
		        "fatherId": 0,
		        "provinceCode": "110000",
		        "cityCode": "110100",
		        "districtCode": "110101",
		        "type": 0,
		        "useType": 0,
		        "token": "eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNrUVslOwzAQ_RefW6HSdElvwIkDEqLcEAcndmlQGkexwyLEv-N67BKoZ1JVIMGlsf1ePdvz2G9MtxlbMC42RcUGrFGlvBRsMRrAkh_Ll9p-J-kkTdJpYhcKbmBhPh2fbhd4a9aqKUwhNVvcve3mr3bzk3rNtTwpC23Y--AbpvO1UqUDz8rymj9IlKP5Ew4KWUqDw6rCodVqH6NcNpLna9kEn29hGnc9cOO-BxRzPuCN1NLUXOtn1QictlGUEdUaiJigVAQWS1OnetfbjJGMfXArt35dHLOzNq2QlQk1WsIUkZfnIvryKCowj_fUKNDiNQpoPMkBrCidxmMDPB4ZYFhc5KFts0eZG8JuYCA59egxth8aLqiIAY_bBQy12ijR5obuRYGEpNSjfSaipQxYTAOHnZR90HVxOiKg9MgXSFhYgMaC8kgsJIDiedyFi3rtGMSfMVcdGPMUADT3W1M3dnAlq3afsrGr7ueK12iFimqljml0_ddnV7kYh1DQ55E6qg93mkHvZbl02_2dK_OAS7HY1KoxfvbzCaKSn5c2AKmRVAQUS0XAIQA_w2nkceuW8UsNz1-XEN6loP2_gPEtlsffFOH314DbTv-XNwEu0Q7FpRpngAb8jNZAbwPpeacTnblDoN_raJfuwviDdOcCVPqwvm2V7NiUkP3Xq404TG2lbYC5kQIV_O5wHEj82hfvB-zRFBbOxmI6mvPJkCcpHyYJnw-zyYgP03w1z5LRbDYdz9j7BwAAAP__.iYHGy20SEBqzFG82FsRXHmQWhiQbHRGvJyQqNq2hrhM",
		        "schoolName": "测试学校",
		        "roleName": "平台管理员",
		        "roleLevel": "1",
		        "firstMenuUrl": "/school"
		    }
		}
	 *
	 *
	 */
	@RequestMapping(value = "login", name = "登录", method = RequestMethod.POST)
	public RestResult login(@RequestBody Map<String,Object> dataMap) throws Exception {

		AdminVo adminVo = null;
		
		String username = MapUtils.getString(dataMap, "username");
		String password = MapUtils.getString(dataMap, "password");
		
		if (username == null || password == null )
		{
			return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
		}
		
		SysAdmin admin = adminService.loginAdmin(username, password);
		
		if (admin == null) {
			return RestResult.ok(admin);
		}

		BaseContextHandler.setAdminId(admin.getAdminId());
		BaseContextHandler.setAdmin(admin);
		BaseContextHandler.setRoleUrls(admin.getRoleUrls());

		adminVo = new AdminVo();
		BeanUtils.copyProperties(admin,adminVo);
		adminVo.setAdminName(admin.getAdminName());

		return RestResult.ok(adminVo);
	}
	
	/**
	 *
	 * @apiGroup sys
	 * @api {post} /sys/logout 用户注销
	 * @apiVersion 1.0.0
	 * @apiName logout
	 *
	 * @apiParam {Map} dataMap 
	 * @apiParamExample 请求示例（json）
	 * {
		     "token": "eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNrUVslOwzAQ_RefW6HSdElvwIkDEqLcEAcndmlQGkexwyLEv-N67BKoZ1JVIMGlsf1ePdvz2G9MtxlbMC42RcUGrFGlvBRsMRrAkh_Ll9p-J-kkTdJpYhcKbmBhPh2fbhd4a9aqKUwhNVvcve3mr3bzk3rNtTwpC23Y--AbpvO1UqUDz8rymj9IlKP5Ew4KWUqDw6rCodVqH6NcNpLna9kEn29hGnc9cOO-BxRzPuCN1NLUXOtn1QictlGUEdUaiJigVAQWS1OnetfbjJGMfXArt35dHLOzNq2QlQk1WsIUkZfnIvryKCowj_fUKNDiNQpoPMkBrCidxmMDPB4ZYFhc5KFts0eZG8JuYCA59egxth8aLqiIAY_bBQy12ijR5obuRYGEpNSjfSaipQxYTAOHnZR90HVxOiKg9MgXSFhYgMaC8kgsJIDiedyFi3rtGMSfMVcdGPMUADT3W1M3dnAlq3afsrGr7ueK12iFimqljml0_ddnV7kYh1DQ55E6qg93mkHvZbl02_2dK_OAS7HY1KoxfvbzCaKSn5c2AKmRVAQUS0XAIQA_w2nkceuW8UsNz1-XEN6loP2_gPEtlsffFOH314DbTv-XNwEu0Q7FpRpngAb8jNZAbwPpeacTnblDoN_raJfuwviDdOcCVPqwvm2V7NiUkP3Xq404TG2lbYC5kQIV_O5wHEj82hfvB-zRFBbOxmI6mvPJkCcpHyYJnw-zyYgP03w1z5LRbDYdz9j7BwAAAP__.iYHGy20SEBqzFG82FsRXHmQWhiQbHRGvJyQqNq2hrhM"
    	}
  	 * 	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": null
		    }
		}
	 *
	 *
	 */
	@RequestMapping(value = "logout", name = "注销", method = RequestMethod.POST)
	public RestResult logout(@RequestBody Map<String,Object> dataMap) throws Exception {
		
		String token = MapUtils.getString(dataMap, "token");
		
		if (token == null)
		{
			return RestResult.error(ExceptionEnum.BADREQUEST.getCode(),ExceptionEnum.BADREQUEST.getMsg());
		}
		
		adminService.logoutAdmin(token);

		BaseContextHandler.remove();

		return RestResult.ok();
	}

	
	
	/**
	 *
	 * @apiGroup sys
	 * @api {get} /sys/menulist 获取用户功能权限列表
	 * @apiVersion 1.0.0
	 * @apiName getUserMenuList
	 *
	 * @apiParam {Long} adminId 管理员ID
 	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": [
		        "/school",
		        "/teacher",
		        "/student",
		        "/phase",
		        "/subject",
		        "/grade",
		        "/product",
		        "/admin",
		        "/role",
		        "/schoolinfo",
		        "/schoolteacher",
		        "/classes",
		        "/schoolstudent",
		        "/schoolrole"
		    ]
		}
	 *
	 *
	 */
	@RequestMapping(value = "menulist", method = { RequestMethod.GET })
	public RestResult getUserMenuList(@RequestParam Long adminId) throws Exception {
	
		List<String> menuList = adminService.getMenuList(adminId);
		
		if (menuList==null)
		{
			menuList = new ArrayList<String>();
		}
		
		return RestResult.ok(menuList);
	}
	
	
	/**
	 *
	 * @apiGroup sys
	 * @api {get} /sys/allmenulist 获取用户功能权限列表 （含父菜单）
	 * @apiVersion 1.0.0
	 * @apiName getAllMenuList
	 *
	 * @apiParam {Long} adminId 管理员ID
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": [
		        "/school",
		        "/teacher",
		        "/student",
		        "/phase",
		        "/subject",
		        "/grade",
		        "/product",
		        "/admin",
		        "/role",
		        "/schoolinfo",
		        "/schoolteacher",
		        "/classes",
		        "/schoolstudent",
		        "/schoolrole"
		    ]
		}
	 *
	 *
	 */
	@RequestMapping(value = "allmenulist", method = RequestMethod.GET)
	public RestResult getALLMenuList(@RequestParam Long adminId) throws Exception {
	
		List<String> menuList = adminService.getAllMenuList(adminId);
		
		if (menuList==null)
		{
			menuList = new ArrayList<String>();
		}
		
		return RestResult.ok(menuList);
	}
	
	/**
	 *
	 * @apiGroup sys
	 * @api {get} /sys/roleUrls 获取用户操作权限URLS
	 * @apiVersion 1.0.0
	 * @apiName getUrlsByRoleId
	 *
	 * @apiParam {Long} roleId 角色ID
	 * 
	 *
	 * @apiSuccessExample Success-Response:
	 * HTTP/1.1 200
		{
		    "code": 200,
		    "msg": "success",
		    "data": "/school/info,/school/listPhase,/phase/list,/schoolproduct/list,/schoolrole/list,/grade/list,/school/listPhase,/subject/list,/teacher/listAllSchoolTeacherPage,/classes/classessubjects,/classes/unselectedTeacher,/classes/selectedTeacher,/classesteacher/save,"
		}
	 *
	 *
	 */
	@RequestMapping(value = "roleUrls", method = RequestMethod.GET)
	public RestResult getUrlsByRoleId(@RequestParam Long roleId) throws Exception {
	
		return RestResult.ok(roleMenuService.getUrlsByRoleId(roleId));
	}
	
	@RequestMapping(value = "403")
	public RestResult getFORBIDDEN(HttpServletRequest request) throws Exception {
	
		return RestResult.error(ExceptionEnum.FORBIDDEN.getCode(),ExceptionEnum.FORBIDDEN.getMsg());
	}

	
}
